﻿(function () {
    "use strict";

    // Create model class
    var modelClass = WinJS.Class.define(function (name) {
        this._initObservable();
        this.name = name;
    },
    (function () {

        var name = Eight.Binding.initProperty("name"),
            isTextboxVisible = Eight.Binding.initProperty("isTextboxVisible", true);

        function handleClick(e, model) {
            console.log(model.name + " clicked");
        }

        return {
            name: name,
            isTextboxVisible: isTextboxVisible,
            handleClick: WinJS.Utilities.markSupportedForProcessing(handleClick)
        };

    }()));

    // Add class to ViewModel Namespace
    WinJS.Namespace.define("ViewModel", {
        // Person class object (model to be instantiated)
        Person: WinJS.Class.mix(modelClass,
            WinJS.Binding.mixin,
            WinJS.Binding.expandProperties(modelClass)),
        // Converter for ensuring the model class is passed to the click handler
        personClickRouter: WinJS.Binding.converter(function convertFunctionToPassModelAndEventArgs(model) {
            return WinJS.Utilities.markSupportedForProcessing(function (e) {
                model.handleClick(e, model);
            });
        })
    });

    // Create the sample which will initialize the bindings
    WinJS.Namespace.define("BindingSample", (function createNS() {

        function init() {
            var binding = document.getElementById("binding"),
                bindingUpdater = document.getElementById("updateFullName"),
                viewModel;

            viewModel = new ViewModel.Person("ferguson");

            WinJS.Binding.processAll(binding, viewModel, true).done(function () {

                // Attach event listener after everything is bound
                updateFullName.addEventListener("click", function (e) {
                    viewModel.name = "Red Ferguson";
                });

            });
        }

        return {
            init: init
        };

    })());
})();